package com.lh7.ledger.utils;

import com.lh7.ledger.pojo.LedgerFields;
import com.lh7.ledger.pojo.LedgerRecords;
import com.lh7.ledger.pojo.RecordValues;

import java.util.*;
import java.util.stream.Collectors;


public class LedgerUtils {

    public static List<Map<String, Object>> buildStructuredLedgerRecords(
            List<LedgerFields> fields,
            List<LedgerRecords> records,
            List<RecordValues> values,
            Map<Long, String> userIdToName
            ) {


        Map<Long, String> fieldIdToName = fields.stream()
                .collect(Collectors.toMap(LedgerFields::getId, LedgerFields::getName));

        Map<Long, Map<String, Map<String, Object>>> recordFieldMap = new LinkedHashMap<>();
        for (RecordValues value : values) {
            Long recordId = value.getRecordId();
            Long fieldId = value.getFieldId();
            String fieldName = fieldIdToName.get(fieldId);

            if (fieldName == null) continue;

            recordFieldMap
                    .computeIfAbsent(recordId, k -> new LinkedHashMap<>())
                    .put(fieldName, Map.of(
                            "fieldId", fieldId,
                            "value", value.getValueString()
                    ));
        }

        List<Map<String, Object>> result = new ArrayList<>();
        for (LedgerRecords record : records) {
            Map<String, Object> item = new LinkedHashMap<>();
            item.put("ledgerId", record.getLedgerId());
            item.put("recordId", record.getId());
            item.put("userId", record.getUserId());
            item.put("userName", userIdToName.getOrDefault(record.getUserId(), "未知"));
            item.put("fields", recordFieldMap.getOrDefault(record.getId(), new LinkedHashMap<>()));
            result.add(item);
        }

        return result;
    }
}



